package repository;

import java.util.*;
import dto.*;
import java.sql.*;


public class ProductRepository 
{
   private DataBase db=null; 
   
   private PreparedStatement sqlGetById;
   private PreparedStatement sqlGetAll;
   private PreparedStatement sqlUpdate;
   private PreparedStatement sqlCreate;
   
   
   public ProductRepository()
   {
       try
       {
           db=new DataBase();
       }
       catch(Exception e){}
   }
   
   
    public boolean Create(Product newProduct)
      {
          try
          {
              sqlCreate=db.connection.prepareStatement("INSERT INTO Products (productName, price, description, onStorage) VALUES (?,?,?,?)");
              sqlCreate.setString(1, newProduct.name);
              sqlCreate.setDouble(2, newProduct.price);
              sqlCreate.setString(3, newProduct.description);
              sqlCreate.setInt(4, newProduct.onStorage);
              int result=sqlCreate.executeUpdate();
              if (result==0)
              {
               db.connection.rollback();
               return false;
              }
              return true;
           }
          catch (Exception e)
          {
              return false;
          }
       }
   
   
   public boolean UpdateProduct(Product p)
   {
       try
       {
        sqlUpdate=db.connection.prepareStatement("UPDATE Products SET onStorage = ? WHERE id = ?");
        sqlUpdate.setInt(1, p.onStorage);
        sqlUpdate.setInt(2, p.id);
        int result=sqlUpdate.executeUpdate();
        if (result==0){
            db.connection.rollback();
            return false;
        }
        return true;
       }
       catch(Exception e)
       {
           return  false;
       }
   }
   
   public List<Product> getAll()
   {
    try
    {
     sqlGetById=db.connection.prepareStatement("SELECT id FROM Products");
     ResultSet resultSet=sqlGetById.executeQuery();
     List<Product> pList=new ArrayList<Product>();
     while (resultSet.next())
      {       
         int gotCurrentId = resultSet.getInt(1);
         Product gotProduct=getById(gotCurrentId);
         pList.add(gotProduct);
      }
    return pList;
    }
    catch(Exception e)
    {return null;}
   }
   
   
   
   public Product getById(int id)
   {
       try
       {
       sqlGetById=db.connection.prepareStatement("SELECT id, productName, price, description, onStorage FROM Products WHERE id = ? ");
       sqlGetById.setInt(1, id);
       ResultSet resultSet=sqlGetById.executeQuery();
       if (!resultSet.next())
       {       
           return null;
       }
       int gotId = resultSet.getInt(1);
       String name=resultSet.getString(2);
       double price = resultSet.getDouble(3);
       String desc=resultSet.getString(4);
       int onStorage=resultSet.getInt(5);
       Product p=new Product(gotId, name, price, desc, onStorage);
       return p;
       }
       catch(Exception e)
       {
           return  null;
       }
    }
}
